package com.hdwe.tools.pm.service.impl;

import cn.hutool.core.date.DateUtil;
import com.hdwe.tools.pm.domain.enums.TaskStatus;
import com.hdwe.tools.pm.domain.vo.PmRequireVo;
import com.hdwe.tools.pm.domain.vo.PmTaskVo;
import com.hdwe.tools.pm.service.IPmRequireService;
import com.hdwe.tools.pm.service.IPmTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.service.ComboboxService;
import org.dromara.common.core.service.ConfigService;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.utils.MarkdownUtil;
import org.dromara.common.core.utils.Threads;
import org.dromara.common.core.utils.WeChatRobot;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hdwe.tools.pm.config.PmConstant.PM_TASK_DETAIL_PATH;

@Slf4j
@RequiredArgsConstructor
@Service
public class ReportService {

    private final IPmTaskService pmTaskService;
    private final IPmRequireService pmRequireService;
    private final ConfigService configService;
    private final ComboboxService comboboxService;
    private final DictService dictService;
    private static final String WEBHOOK_URL_DEV = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1a4547e3-f510-402f-a3f5-ec59a191b4de";
    private static final String WEBHOOK_URL_PRO = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=026822ab-3bb1-4a8b-9a12-d45aedc14ef5";

    /**
     * 每天下午5点发送日报
     */
    @Scheduled(cron = "0 0 17 * * ?")
    public void sendDailyReportDev() {
        String users = configService.getConfigValue("report.daily.user");
        Arrays.stream(users.split(",")).forEach(userId -> {
            List<PmTaskVo> dailyTasks = pmTaskService.queryDailyReport(Long.valueOf(userId));
            sendReport(WEBHOOK_URL_DEV, "日报", userId, dailyTasks);
        });
    }

    /**
     * 每天下午5点35发送日报到工作群
     */
    @Scheduled(cron = "0 35 17 * * ?")
    public void sendDailyReportPro() {
        String users = configService.getConfigValue("report.daily.user");
        Arrays.stream(users.split(",")).forEach(userId -> {
            List<PmTaskVo> dailyTasks = pmTaskService.queryDailyReport(Long.valueOf(userId));
            sendReport(WEBHOOK_URL_PRO, "日报", userId, dailyTasks);
        });
    }

    /**
     * 每天早上8点发送当日需处理的任务
     */
    @Scheduled(cron = "0 0 9,17 * * ?")
    public void sendDailyWork() {
        String users = configService.getConfigValue("report.daily.user");
        Arrays.stream(users.split(",")).forEach(userId -> {
            List<PmTaskVo> dailyTasks = pmTaskService.queryDailyWork(Long.valueOf(userId));
            String userName = comboboxService.queryLabel(CacheNames.COMBOBOX_USER, userId);
            String header = MarkdownUtil.createHeader(1, userName) + "`规划开始时间，改状态！`\n";
            List<String> taskContent = dailyTasks.stream()
                .map(task -> {
                    String titleLink = MarkdownUtil.createLink(task.getTitle(), PM_TASK_DETAIL_PATH + task.getId());
                    String startTime = DateUtil.format(task.getStartDate(), "yyyy-MM-dd");
                    String endTime = DateUtil.format(task.getEndDate(), "yyyy-MM-dd");
                    String status = TaskStatus.markdown(task.getStatus());
                    return titleLink + " " + startTime + "~" + endTime + " " + status;
                })
                .collect(Collectors.toList());
            WeChatRobot.sendMarkdownMessage(ReportService.WEBHOOK_URL_DEV, header, taskContent);
            log.info("发送" + userName + "的" + "需处理的任务" + "成功");
            Threads.sleep(30000);
        });
    }

    /**
     * 每天下午6点发送当日客户需求进度
     */
    @Scheduled(cron = "0 0 18 * * ?")
    public void sendClientReport() {
        // 查询客户需求列表
        List<PmRequireVo> requireList = pmRequireService.queryRequireProgress();
        // 按租户分组，发送消息
        requireList.stream().collect(Collectors.groupingBy(PmRequireVo::getTenantId))
            .forEach((tenantId, requires) -> {
                String tenantName = comboboxService.queryLabel(CacheNames.COMBOBOX_TENANT, tenantId);
                String header = MarkdownUtil.createHeaderN(1, tenantName + " 需求进度");
                // 生成需求内容
                List<String> requireContent = requires.stream().flatMap(require -> {
                    String titleLink = MarkdownUtil.createLink(require.getTitle(), PM_TASK_DETAIL_PATH + require.getId());
                    String endDate = DateUtil.format(require.getEndDate(), "yyyy-MM-dd");
                    // 查询任务列表
                    List<PmTaskVo> tasks = pmTaskService.queryRequireTasks(require.getId());
                    // 如果没有任务，则不发送
                    if (tasks.isEmpty()) {
                        return Stream.empty();
                    }
                    List<String> taskContent = tasks.stream().map(task -> {
                        String taskTitleLink = MarkdownUtil.createLink(task.getTitle(), PM_TASK_DETAIL_PATH + task.getId());
                        return taskTitleLink + " " + TaskStatus.markdown(task.getStatus());
                    }).toList();
                    // 计算完成比例
                    long finishedCount = tasks.stream().filter(task -> TaskStatus.FINISHED.getCode().equals(task.getStatus())).count();
                    String finishedRate = String.format("%.2f", (double) finishedCount / tasks.size() * 100);
                    // 生成阻塞任务内容
                    String taskBody = MarkdownUtil.createQuoteUnorderedList(taskContent);
                    // 拼接消息内容
                    return Stream.of(titleLink + " 截止时间：" + endDate + " 完成比例：" + finishedRate + "%\n" + taskBody);
                }).collect(Collectors.toList());
                // 只发送有任务的需求消息
                if (!requireContent.isEmpty()) {
                    WeChatRobot.sendMarkdownMessage(WEBHOOK_URL_PRO, header, requireContent);
                }
            });
    }

    /**
     * 每周一早上9点发送周报
     */
    @Scheduled(cron = "0 0 9 ? * MON")
    public void sendWeeklyReport() {
        String users = configService.getConfigValue("report.daily.user");
        Arrays.stream(users.split(",")).forEach(userId -> {
            List<PmTaskVo> weeklyTasks = pmTaskService.queryWeeklyTasks(Long.valueOf(userId));
            sendReport(WEBHOOK_URL_DEV,"周报", userId, weeklyTasks);
        });
    }

    private void sendReport(String webhook, String reportType, String userId, List<PmTaskVo> tasks) {
        String userName = comboboxService.queryLabel(CacheNames.COMBOBOX_USER, userId);
        String header = MarkdownUtil.createHeaderN(1, userName + " " + reportType);
        List<String> taskContent = tasks.stream()
            .map(task -> {
                String titleLink = MarkdownUtil.createLink(task.getTitle(), PM_TASK_DETAIL_PATH + task.getId());
                String startTime = DateUtil.format(task.getStartDate(), "yyyy-MM-dd");
                String costTime = task.getCostTime() == null ? "" : task.getCostTime() > 24 ? task.getCostTime() / 24 + "天" : task.getCostTime() + "小时";
                String status = TaskStatus.markdown(task.getStatus());
                return titleLink + " " + startTime + " " + status + " " + costTime;
            })
            .collect(Collectors.toList());
        WeChatRobot.sendMarkdownMessage(webhook, header, taskContent);
    }

}
